﻿using HK.Core.Serializable.Attribute;
using HK.Editor.Serializable.Protocol.Drawer;
using HK.Editor.Utils;
using UnityEditor;
using UnityEngine;

namespace HK.Editor.Serializable.Drawer
{
    
    /// <summary>
    /// Drawer - Group视图
    /// </summary>
    [CustomPropertyDrawer(typeof(GroupViewAttribute))]
    public class GroupViewDrawer : GUIPropertyDrawer<GroupViewAttribute>, IGroupViewDrawer
    {
        
#region Size&Rect
        
        /// <summary>
        /// 取得Property的高度
        /// </summary>
        /// <param name="iProperty">Property</param>
        /// <param name="iLabel">文本</param>
        /// <returns>Property的高度</returns>
        public override float GetPropertyHeight(SerializedProperty iProperty, GUIContent iLabel)
        {
            var totalHeight = 0.0f;
            if (!iProperty.isExpanded)
            {
                totalHeight = HeaderHeight;
            }
            else
            {
                if (!DrawFromUnity)
                {
                    totalHeight += 2;
                }
                totalHeight = HeaderHeight;
                totalHeight += 2;
                var copy = iProperty.Copy();
                var end = copy.GetEndProperty();
                var nextVisible = copy.NextVisible(true);

                var validCount = 0;
                while (nextVisible && !SerializedProperty.EqualContents(copy, end))
                {
                    totalHeight += EditorGUI.GetPropertyHeight(copy, GUIContent.none, copy.isExpanded) + 1;
                    nextVisible = copy.NextVisible(false);
                    ++validCount;
                }

                if (0 < validCount)
                {
                    totalHeight += 1;
                }
                totalHeight += 6;
            }

            TotalHeight = totalHeight;
            return TotalHeight; 
        }

#endregion

#region Events

        /// <summary>
        /// 展开
        /// </summary>
        /// <param name="iSelfProperty">自身Property</param>
        /// <param name="iIsExpanded">展开/缩进</param>
        protected override void ExpandChildren(SerializedProperty iSelfProperty, bool iIsExpanded)
        {
            if(null == iSelfProperty) return;
            iSelfProperty.isExpanded = iIsExpanded;
                            
            base.ExpandChildren(iSelfProperty, iIsExpanded);
        }

#endregion

        
    }
}
